
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

from libs.sinaweibopy3 import weiboApi
from oauth.models import OauthUser
from user.models import User
from user.utils import jwt_response_payload_handler


class OauthWeibo(APIView):
    # 自定义权限类
    permission_classes = (AllowAny,)

    def post(self, request):
        # 返回 微博登录地址
        url = weiboApi.get_authorize_url()
        return Response({"code": "0", "msg": "成功", "data": {'url': url}})


class OauthWeiboCallback(APIView):
    # 自定义权限类
    permission_classes = (AllowAny,)

    def post(self, request):
        # 接受code
        code = request.data.get('code')
        # 1.根据code 换取 access_token
        data = weiboApi.request_access_token(code)
        print('这个data是', data)
        access_token = data.access_token
        weibo_uid = data.uid
        # 2.根据uid查询绑定情况
        try:
            oauth_user = OauthUser.objects.get(uid=weibo_uid, oauth_type='1')
        except Exception as e:
            oauth_user = None
        if oauth_user:
            # 3. 如果绑定了，就返回token，登录成功
            user = oauth_user.user
            print('oauth_user.user---',user)

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            data = jwt_response_payload_handler(token, user)
            data['type'] = '0'
            return Response({'code': 0, 'msg': '登录成功', 'data': data})
        else:
            # 如果没绑定，返回标志，让前端跳转到绑定页面
            return Response({'code': 0, "msg": '授权成功', "data": {"type":'1','uid': weibo_uid}})


class OauthWeiboBindUser(APIView):
    permission_classes = (AllowAny,)

    def post(self, request):
        # 绑定用户, 1. 已注册用户, 2. 未注册用户
        # 1.1 获取用户名, 密码, weibo_uid
        username = request.data.get('username')
        password = request.data.get('password')
        weibo_uid = request.data.get('weibo_uid')
        if not all([username, password, weibo_uid]):
            return Response({'code': 999, 'msg': '参数不全'})
        # 0.判断是否存在此用户
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            user = None
# 类的代码是二进制的，已经写进去python解释器里面了，
        if user:
            # 1.2 , 如果存在就验证 密码, 验证通过,就绑定, 返回token,登录成功
            if user.check_password(password):
                ou = OauthUser(uid=weibo_uid, user=user, oauth_type='1')
                ou.save()
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                data = jwt_response_payload_handler(token, user)
                data['type'] = '0'  # 指定为登录成功
                return Response({'code': 0, 'msg': '登录成功', 'data': data})
            else:
                return Response({'code': 999, 'msg': '密码错误'})
        else:

            # 2. 未注册用户
            # 2.1 生成新用户, 设置用户名密码, 保存, 然后绑定, 返回token, 登录成功
            user = User(username=username)
            user.set_password(password)
            user.save()
            ou = OauthUser(uid=weibo_uid, user=user, oauth_type='1')
            ou.save()
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            data = jwt_response_payload_handler(token, user)
            data['type'] = '0'  # 指定为登录成功
            return Response({'code': 0, 'msg': '登录成功', 'data': data})


